<template>
    <div>
      <div class="q-pa-sm q-gutter-y-sm">
<!--        Loading-->
        <q-linear-progress stripe indeterminate style="height: 1px" v-show="loading"/>
<!--        toolbar-->
        <q-toolbar class="text-primary">
          <q-btn flat round dense icon="add" @click="onClickLeft"/>
          <q-toolbar-title @click="queryBooklist">
            iNeed.Novel
          </q-toolbar-title>
          <q-btn flat round dense icon="account_circle" @click="onClickRight" :label="rightClickStr"/>
        </q-toolbar>
<!--        search-->
        <q-input v-model="searchValue"  rounded outlined type="text" class="qsearch">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
<!--        fastLink-->
        <q-chip color="deep-orange" clickable text-color="white" icon="directions"  @click="tocontentByNotice" v-show="noticeShow">
          {{'继续阅读《'+noticeBean.bookName+'》'+noticeBean.title}}
        </q-chip>
<!--        list Loading-->
        <q-item v-show="booklistLoading" v-for="index in 8" :key="index">
          <q-item-section avatar>
            <q-skeleton type="QBtn" />
          </q-item-section>

          <q-item-section>
            <q-item-label>
              <q-skeleton type="text" />
            </q-item-label>
            <q-item-label caption>
              <q-skeleton type="text" width="65%" />
            </q-item-label>
          </q-item-section>
        </q-item>
<!--        list-->
        <q-splitter
          v-model="splitterModel"
          v-show="booklist"
          style="height:75vh"
        >
          <template v-slot:before>
            <q-tabs
              v-model="tab"
              vertical
              class="text-teal"
            >
              <q-tab name="搜索" label="搜索" v-show="searchValue"/>
              <q-tab v-for="type in booklisttypes" :key="type" :name="type"  :label="type" />
            </q-tabs>
          </template>
          <template v-slot:after>
            <q-tab-panels
              v-model="tab"
              animated
              transition-prev="jump-up"
              transition-next="jump-up"
            >
              <q-tab-panel name="搜索">
                <div style="max-width: 90%;">
                  <q-list
                    v-for="item in booklist" :key="item.id" v-show="searchValue && item._show">
                    <q-item  v-ripple style="width: 80%;float: left">
                      <q-item-section @click="toContentList(item)">
                        <q-item-label  lines="1">{{item.bookName}}</q-item-label>
                      </q-item-section>
                    </q-item>
<!--                    <q-item style="width: 18%;float: left">-->
<!--                      <q-btn flat  color="primary"  label="X" @click="deleteNovelBook"/>-->
<!--                    </q-item>-->
                    <q-separator style="width: 100%;float: left"/>
                  </q-list>
                </div>
              </q-tab-panel>
              <q-tab-panel v-for="(items,key) in booklistmap" :key="key" :name="key">
                <div style="max-width: 90%;">
                  <q-list
                    v-for="item in items" :key="item.id"
                  >
                    <q-item  v-ripple style="width: 80%;float: left">
                      <q-item-section @click="toContentList(item)">
                        <q-item-label  lines="1">{{item.bookName}}</q-item-label>
                      </q-item-section>
                    </q-item>
                    <q-item style="width: 18%;float: left">
                      <q-btn flat  color="primary"  label="X" @click="deleteNovelBook(item.id)"/>
                    </q-item>
                    <q-separator style="width: 100%;float: left"/>
                  </q-list>
                </div>
              </q-tab-panel>
            </q-tab-panels>
          </template>

        </q-splitter>

      </div>
    </div>
</template>
<script>
import axios from 'axios'
import { nlocalstorage } from '../util/localstorage.js'
import { pageUrl } from '../util/pageUrl.js'
import { Plugins } from '@capacitor/core'
const { App } = Plugins
import { Cookies } from 'quasar'

var browser = {
  versions: (function () {
    var u = navigator.userAgent
    return { // 移动终端浏览器版本信息
      trident: u.indexOf('Trident') > -1, // IE内核
      presto: u.indexOf('Presto') > -1, // opera内核
      webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
      mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或uc浏览器
      iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
      iPad: u.indexOf('iPad') > -1, // 是否iPad
      // eslint-disable-next-line eqeqeq
      webApp: u.indexOf('Safari') == -1 // 是否web应该程序，没有头部与底部
    }
  }()),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
}

export default {
  name: 'booklist',
  data () {
    return {
      loading: true,
      booklistLoading: true,
      booklist: null,
      booklistmap: {},
      booklisttypes: [],
      searchValue: '',
      rightClickStr: '登陆',

      actionShow: false,
      actions: [
        { name: '注销', type: 'logout' }
      ],
      noticeShow: false,
      noticeBean: {},
      overLayShow: false,
      tab: '推荐',
      splitterModel: 20
    }
  },
  watch: {
    searchValue () {
      const v = this.searchValue
      const map = this.booklistmap
      for (const key in map) {
        const list = this.booklistmap[key]
        list.forEach(item => {
          item._show = !v || v === '' || item.bookName.indexOf(v) !== -1
        })
      }
      if (v != null && v != '') {
        this.tab = '搜索'
      }
    },
    '$route.path': function (newVal) {
      if (newVal === '/index') {
        this.queryLastRead()
      }
    }
  },

  mounted () {
    this.checkBrow()
    this.queryBooklist()
    this.queryUser()
    // 监听安卓手机返回键
    if (this.$q.platform.is.capacitor) {
      // 监听返回按钮
      document.addEventListener('backbutton', this.fun)
    }
  },
  destroyed () {
    if (this.$q.platform.is.capacitor) {
      window.removeEventListener('backbutton', this.fun)
    }
  },
  methods: {
    fun () {
      if (this.$route.path === '/index' || this.$route.path === '/') {
        App.exitApp()
      }
    },
    checkBrow () { // 检查浏览器
      if (browser.versions.mobile) { // 判断是否是移动设备打开。browser代码在下面
        var ua = navigator.userAgent.toLowerCase()// 获取判断用的对象
        if (ua.match(/MicroMessenger/i) === 'micromessenger') {
          // 在微信中打开
          this.overLayShow = true
        }
        if (ua.match(/WeiBo/i) === 'weibo') {
          // 在新浪微博客户端打开
          // 在微信中打开
          this.overLayShow = true
        }
        if (ua.match(/QQ/i) === 'qq') {
          // 在QQ空间打开
          // 在微信中打开
          this.overLayShow = true
        }
        if (browser.versions.ios) {
          // 是否在IOS浏览器打开
        }
        if (browser.versions.android) {
          // 是否在安卓浏览器打开
        }
      } else {
        // 否则就是PC浏览器打开
      }
    },
    queryLastRead () {
      const _this = this
      if (!_this.$simpleStore.state.userInfo) {
        return
      }
      axios({
        url: pageUrl.queryLastRead
      }).then(res => {
        if (res.data.state === 'success' && res.data.obj) {
          _this.noticeBean = res.data.obj
          _this.noticeShow = true
        }
      })
    },
    queryBooklist () {
      const _this = this
      _this.loading = true
      _this.booklistLoading = true
      axios({
        url: '/novelBook/book/list'
      }).then(res => {
        if (res.data.state === 'success') {
          const list = res.data.obj
          const sc = '推荐', scByUser = '收藏', tj = '推荐'
          const map = {}
          map[sc] = []
          map[scByUser] = []
          map[tj] = []
          const listtype = [scByUser, sc]
          _this.booklist = list
          list.forEach(item => {
            item._show = true
            if (item.isCollection && item.isCollection === 1) {
              map[sc].push(item)
            }
            if (item.isUserCollection && item.isUserCollection === 1) {
              map[scByUser].push(item)
            }
            if (!item.category) {
              item.category = '**'
            }
            if (!map[item.category]) {
              map[item.category] = []
              listtype.push(item.category)
            }
            map[item.category].push(item)
          })
          _this.booklistmap = map
          _this.booklisttypes = listtype
        }
      }).finally(() => {
        _this.loading = false
        _this.booklistLoading = false
      })
    },
    /* 跳跃到读小说页面 */
    toContentList (item) {
      const to = { path: '/bookcontentlist/' + item.id + '/' + item.bookName }
      this.loading = true
      nlocalstorage.set('book', item)
      this.$router.push(to).catch(() => {})
      this.loading = false
    },
    /* 删除小说 */
    deleteNovelBook (id) {
      const _this = this

      this.$q.dialog({
        title: '确认',
        message: '确认删除?',
        cancel: true,
        persistent: true
      }).onOk(() => {
        // console.log('>>>> OK')
      }).onOk(() => {
        _this.loading = true
        axios({
          url: pageUrl.addCollection,
          params: {
            bookId: id,
            type: 0
          }
        }).then(res => {
          if (res.data.state === 'success') {
            if (res.data.obj < 0) {
              _this.$q.notify({
                message: '服务异常'
              })
            } else {
              _this.$q.notify({
                message: '删除成功'
              })
              _this.queryBooklist()
            }
          } else {
            _this.$q.notify(res.data.message)
          }
        }).catch(() => {
          _this.$q.notify({
            message: '服务异常'
          })
        }).finally(() => {
          _this.loading = false
        })
      }).onCancel(() => {
        // console.log('>>>> Cancel')
      }).onDismiss(() => {
        // console.log('I am triggered on both OK and Cancel')
      })
    },
    onClickLeft () {
      this.$router.push('/searchNewBook').catch(() => {})
    },
    onClickRight () {
      if (this.rightClickStr === '登陆') {
        if (this.$simpleStore.state.userInfo) {
          this.rightClickStr = this.$simpleStore.state.userInfo.userName
        } else {
          this.$router.replace('/login').catch(() => {})
        }
      } else {
        // 注销
        this.$q.bottomSheet({
          actions: [
            {
              label: '注销',
              icon: 'logout',
              id: 'logout',
              color: 'primary'
            }
          ]
        }).onOk(action => {
          if (action.id === 'logout') {
            axios({
              url: 'intUser/logout'
            })
            this.rightClickStr = '登陆'
            this.$simpleStore.clearUserInfo()
            nlocalstorage.remove('intUserToken')
          }
        }).onCancel(() => {
          // console.log('Dismissed')
        }).onDismiss(() => {
          // console.log('I am triggered on both OK and Cancel')
        })
        // this.actionShow = true
      }
    },
    queryUser () {
      const _this = this
      let i = -1
      const dsq = setInterval(function () {
        i += 1
        const a = i % 3
        let str = ''
        if (a === 0) {
          str = '.'
        }
        for (let j = 0; j <= a; j++) {
          str += '.'
        }
        _this.rightClickStr = str
      }, 1000)
      const fromCookieToken = Cookies.get('intUserToken')
      nlocalstorage.get('intUserToken', function (fromLocalstorageToken) {
        if (!fromCookieToken && fromLocalstorageToken) {
          Cookies.set('intUserToken', fromLocalstorageToken)
        }
      })
      axios({
        url: pageUrl.queryUserByToken
      }).then(res => {
        if (res.data.state === 'success' && res.data.obj) {
          _this.$simpleStore.setUserInfo(res.data.obj)
          _this.rightClickStr = res.data.obj.userName
          this.queryLastRead()
        } else {
          _this.rightClickStr = '登陆'
        }
      }).catch(() => {
        _this.rightClickStr = '登陆'
      }).finally(() => {
        clearInterval(dsq)
      })
    },
    actionSelect (event) {
      if (event.type === 'logout') {
        axios({
          url: 'intUser/logout'
        })
        this.rightClickStr = '登陆'
        this.$simpleStore.clearUserInfo()
      }
      this.actionShow = false
    },
    tocontentByNotice () {
      if (this.noticeBean) {
        var item = this.noticeBean
        var to = '/bookcontent/' + item.id + '/' + item.bookName + '/' + item.title
        this.$router.push(to).catch(() => {})
      }
    }
  }

}
</script>

<style scoped>
    .wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
    }
    .block {
        width: 200px;
        height: 120px;
        color: #fff;
    }
</style>
